"use strict";
var page = require("webpage").create(),
    args = require('system').args,
    fs = require('fs'),
    siteurl = "http://jxzlxt.jhc.cn/",
    datadir = './data';

page.viewportSize = {width: 1024, height: 800};

var username, password, flow;
if(args.length != 3) {
  console.log('You must provide username, password.');
  phantom.exit();
} else {
  username = args[1];
  password = args[2];
}

var flow = [list_page, first_log, fill_log, reset];

//输出浏览器的控制台输出，调试时很有帮助。
page.onConsoleMessage = function(msg) {
  console.log('CONSOLE: ' + msg);
};

page.onLoadFinished = function(status) {
  if(status !== 'success') {
    console.log('Unable to open ' + page.url);
    phantom.exit();
  }
  console.log("onLoadFinished: " + page.url);
  //如果是登录页，则直接调用login()
  if(page.url === siteurl) {
    login();
    return;
  }
//  page.render(Date.now + '.png');
  //从flow找出下一步操作，并执行
  var next_op = flow.shift();
  console.log("next_op: " + next_op.name);
  next_op();
}

page.open(siteurl);

function login(){
  page.evaluate(function(uname, pass){
    $('#yhlx').val('1');
    $('#yhm').val(uname);
    $('#mm').val(pass);
    $('#btn_dl_c').click();
  }, username, password);
}

//点击填写教学日志
function list_page(){
  setTimeout(function(){
    page.evaluate(function(){
      //有多项菜单名为"填写教学日志"，需特殊处理。
      //var plan_selector = 'ul.fancy-rollovers:nth-child(2) > li:nth-child(2) > ul:nth-child(2) > li:nth-child(2) > ul:nth-child(2) > li:nth-child(1) > a:nth-child(1)';
      var plan_selector = '#main-nav > li:nth-child(2) > ul:nth-child(2) > li:nth-child(2) > ul:nth-child(2) > li:nth-child(1) > a:nth-child(1)';
      $(plan_selector).click();
    });
  }, 1000);
}

function first_log() {
  //加载日志数据完成大约需要5秒多的时间。每隔3秒测试日志是否已经取到，最多重试4次。
  var count = 0;
  var interval = setInterval(function(){
    if(count > 4) {
      console.log("Tried too many times. This script will stop." );
      page.render('nolog.png');
      clearInterval(interval);
      //这里是填写教学日志流程的出口。
      phantom.exit();
    }
    count++;
    if(first_log_item_exists()) {
      clearInterval(interval);
      select_first_log_item();
    } else {
      console.log("Cannot find any log items. Try again.");
    }
  }, 3000);
}
//判断是页面中是否有日志
function first_log_item_exists() {
  var flag = false;
  flag = page.evaluate(function(){
    var first_check = $('#tabGrid_0 tr:nth-child(2) input[type=checkbox]');
    console.log("first_check length: " + first_check.length);
    return first_check.length == 1 ? true : false;
  });
//  page.render('check.png');
  return flag;
}

//选择第一条教学日志
function select_first_log_item() {
  page.evaluate(function(){
    $('#tabGrid_0 tr:nth-child(2) input[type=checkbox]').click();
    $('#btn_txjxrz').click();
    //需要等1秒钟左右，会有对话框弹出。
    setTimeout(function(){
      var btn = $('.modal-footer button:nth-child(1)');
      console.log("Button: " + btn.text().trim() + " will be clicked.");
      btn.click();
    },1000);
  });
//  setTimeout(function(){page.render('select_log.png');},1100);
}

//填写教学日志
function fill_log() {
  var course_name = page.evaluate(function(){
    return $('#rows_1_1_td label').text().trim();
  });
  console.log("course_name: " + course_name);
  if(course_name === undefined || course_name === ''){
    page.render('no_course_name.png');
    phantom_exit();
  }
  var plans = fs.read('./data/' + course_name + '.json');
  page.evaluate(function(page_plans){
    var pattern = /.*(\d\d)-(\d\d)$/;
    var course_date = $('#rows_5_1_td label').text().trim();
    var cname = $('#rows_1_1_td label').text().trim();
    console.log("course_date: " + course_date);
    //从"2017-10-21"中抽取月份与日期
    var arr = pattern.exec(course_date);
    var month = arr[1];
    var day = arr[2];
    if(!month || !day) {
      console.log("Cannot extract month or day from: " + course_date);
      return;
    }
    console.log('month=' + month + ', day=' + day);
    var page_plan_items = JSON.parse(page_plans);
//    console.log(page_plan_items);
    var fill_content = page_plan_items[month];
    if(!fill_content) {
      console.log('fill_content not exits.');
      phantom.exit();
    }
    //填入日志
    $('#SKNR_3').val(fill_content);
    //点击保存按钮
    $('.form-actions button:nth-child(1)').click();
    //弹出对话框中点击确定
    setTimeout(function(){
      $('.modal-footer button:nth-child(2)').click();
    }, 200);
  }, plans);
//  page.render('fill.png');
}

function reset() {
  flow.unshift(reset);
  flow.unshift(fill_log);
  flow.unshift(first_log);
  flow.unshift(list_page);
  page.open('http://jxzlxt.jhc.cn/xtgl/menu_index.html');
}

function phantom_exit(){
  page.close();
  setTimeout(function(){
    phantom.exit();
  },100);
}
